package com.linkallcloud.web.vc;

import java.time.Duration;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.data.redis.core.RedisTemplate;

import com.linkallcloud.core.lang.Strings;
import com.linkallcloud.web.utils.Controllers;

public class ReidsValidateCode extends ValidateCode {

    private RedisTemplate<String, String> redisTemplate;

    public ReidsValidateCode(RedisTemplate<String, String> redisTemplate) {
        super();
        this.redisTemplate = redisTemplate;
    }

    public ReidsValidateCode(RedisTemplate<String, String> redisTemplate, boolean numeric, int securityCodeLength,
            int imageWidth, int imageHight) {
        super(numeric, securityCodeLength, imageWidth, imageHight);
        this.redisTemplate = redisTemplate;
    }

    public ReidsValidateCode(RedisTemplate<String, String> redisTemplate, boolean numeric) {
        super(numeric);
        this.redisTemplate = redisTemplate;
    }

    @Override
    protected void storageSecurityCode(HttpServletRequest request, HttpServletResponse response, String code) {
        String key = UUID.randomUUID().toString();
        Controllers.sendCookie(SECURITY_CODE_KEY, key, null, request, response);
        redisTemplate.opsForValue().set(key, code, Duration.ofMinutes(5));
    }

    @Override
    protected String getStoragedSecurityCode(HttpServletRequest request, HttpServletResponse response) {
        String key = Controllers.getCookie(SECURITY_CODE_KEY, request);
        if (!Strings.isBlank(key)) {
            if (redisTemplate.hasKey(key)) {
                String code = redisTemplate.opsForValue().get(key);
                redisTemplate.delete(key);
                return code;
            }
        }
        return null;
    }

}
